﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractMes;
using HamcoWcs.DAL;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.DeviceMsgQueues;
using HamcoWcs.Models.DeviceMsgs;
using HamcoWcs.Models.Devices;
using System.Linq;

namespace HamcoWcs.Service.Pcon.PconPlcDbMsgParsers
{
    /// <summary>
    /// 请求切换出库模式
    /// </summary>
    public class PconMsgParse_OutMode : PconMsgParseBase
    {
        public override EnumPconPlcRequest RequestType => EnumPconPlcRequest.OutMode;
        private readonly ILoggerService _logger;

        public PconMsgParse_OutMode(ILoggerService logger, IMapper mapper, WcsDbContext wcsDbContext, IMesCommunicateService mesCommunicateService)
            : base(mesCommunicateService, wcsDbContext, mapper)
        {
            _logger = logger;
        }

        public override void Deal(PconDto pconDto, PconPlc pconPlc)
        {
            var isGoods = pconDto.Machine.Pcons.Any(x => x.IsGoods == 1);

            if (isGoods)
            {
                _logger.AddWcsRunLog("device", $"{pconDto.DeviceName}切换出库模式失败，线体有载荷");
                RejectChangeMode(pconDto,5);
            }
            else
            {
                _mesCommunicateService.MachineModeChangeRequest(pconDto, "OUT");

                var pconSendMsg = new PconSendMsg()
                {
                    PconName = (ushort)pconDto.PconName,
                    Request = (ushort)EnumPconSendMsg.ChangeOutModeCmd
                };

                if (pconDto.PconType == EnumPconType.Wharf)
                {
                    pconDto.PortState = "LR";
                    _mesCommunicateService.PortTransferStateChanged(pconDto);
                }

                InsertMsgQueue(new DeviceMsgQueueDto(pconDto, pconSendMsg));

                _logger.AddWcsRunLog("device", $"{pconDto.DeviceName}向MES发送切换出库库模式请求");
            }
        }
    }
}
